package com.luoy.token;

import io.jsonwebtoken.*;
import org.joda.time.DateTime;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;

/**
 * @author LUOYUAN
 * @create 2019-03-07-16:29
 */
public class JwtTokenUtil {

    //生成Token
    public static String generatorToken(JwtInfo jwtInfo,int expire){

        String compact = Jwts.builder().claim(JwtConstants.JWT_KEY_USER_ID, jwtInfo.getUid())
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())//设置过期时间
                .signWith(SignatureAlgorithm.HS256,getKeyInstance()).compact();
        return compact;
    }

    private static Key getKeyInstance(){
        SignatureAlgorithm hs256 = SignatureAlgorithm.HS256;
        byte[] luoys = DatatypeConverter.parseBase64Binary("luoy");
        return new SecretKeySpec(luoys,hs256.getJcaName());
    }
    //根据token获取token的信息
    public static JwtInfo getTokenInfo(String token){
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        return new JwtInfo(body.get(JwtConstants.JWT_KEY_USER_ID).toString());
    }

    public static void main(String[] args) {
        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setUid("1");
//      String s = JwtTokenUtil.generatorToken(jwtInfo, 60);
//      System.out.println("==="+s);
//eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIxIiwiZXhwIjoxNTY0ODI0MTk2fQ.ce63vFX5V5pUUPPtMW_nePrlE7ATQchSXQ9ZYqlu_nM
        JwtInfo tokenInfo = getTokenInfo("eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIxIiwiZXhwIjoxNTY0ODI0NDA4fQ.RatXo801Fsf78lkJIznaMVrjC-AFuZY-J97Z1eFhpfg");

        System.out.println("===:"+tokenInfo);
    }
}
